package org.wolfengi.handler.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;

public class ConfigUtil {
    private static String sep = File.separator;
    public static String conf = System.getProperty("user.dir") + sep + "config" + sep;
    public static String path = System.getProperty("user.dir") + sep;
    private static Properties properFile = new Properties();
    private static Properties prop = new Properties();

    private static Logger logger = LoggerFactory.getLogger(ConfigUtil.class);

    static {
        try {
            properFile.load(getResourceAsStream("application.properties"));
            prop.load(getResourceAsStream("application.properties"));
        } catch (IOException e) {
            logger.debug("加载配置文件失败");
            e.printStackTrace();
        }
    }

    private ConfigUtil() {

    }

    public static InputStream getResourceAsStream(String key) {
        try {
//            return new FileInputStream(new File(System.getProperty("user.dir") + sep + key));
            //先加载jar同目录config下配置
            return new FileInputStream(new File(conf + key));
        } catch (Exception e) {
            try {
                //再加载jar同目录下配置
                return new FileInputStream(new File(path + key));
            } catch (Exception e1) {
                logger.debug("jar 外部加载配置文件失败！");
                try {
                    logger.debug("加载默认配置文件！");
                    return ConfigUtil.class.getClassLoader().getResourceAsStream(key);
                } catch (Exception e2) {
                    logger.debug("jar 內部加载配置文件失败！");
                    e2.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 取出Property，但以System的Property优先,取不到返回空字符串.
     */
    private static String getValue(String key) {
        String systemProperty = System.getProperty(key);
        if (systemProperty != null) {
            return systemProperty;
        }
        if (prop.containsKey(key)) {
            return prop.getProperty(key);
        }
        return "";
    }

    /**
     * 取出String类型的Property，但以System的Property优先,如果都为Null则抛出异常.
     */
    public static String getProperty(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return value;
    }
}
